<template>
  <div class="bed-type-container">
    <!-- 顶部操作栏 -->
    <el-row :gutter="10" class="mb-4">
      <el-col :span="24">
        <el-button type="primary" @click="openAddFloorDialog()">新增楼层</el-button>
        <el-button 
          type="primary" 
          @click="openAddRoomDialog(null)" 
          :disabled="!currentFloorId"
        >新增房间</el-button>
      </el-col>
    </el-row>

    <!-- 楼层Tab栏 -->
    <el-tabs 
      v-model="activeFloorKey" 
      type="card" 
      v-if="floorList.length > 0" 
      style="margin-top: 20px;"
    >
      <el-tab-pane
        v-for="floor in floorList"
        :key="floor.id"
        :name="floor.id.toString()"
        :closable="false"  
      >
        <!-- 楼层标签：名称 + 编辑/删除按钮（独立拆分） -->
        <template #label>
          <div class="tab-label" :class="{ 'active': activeFloorKey == floor.id }">
            <span class="floor-name">{{ floor.floorName }}</span>
            <div class="floor-actions">
              <!-- 编辑按钮 -->
              <el-button 
                link
                size="small" 
                @click.stop="openAddFloorDialog(floor)"
                class="floor-edit-btn"
                style="width: 30px;margin-left: 80px;"
              >
                <el-icon><Edit /></el-icon>
                编辑
              </el-button>
              <!-- 删除按钮 -->
              <el-button 
                link
                size="small" 
                @click.stop="deleteFloor(floor)"
                class="floor-delete-btn"
                type="danger"
                style="width: 30px;"
              >
                <el-icon><Delete /></el-icon>
                删除
              </el-button>
            </div>
          </div>
        </template>

        <!-- 床位状态筛选 -->
        <el-radio-group v-model="bedStatus" class="mb-3">
          <el-radio :label="0">空闲</el-radio>
          <el-radio :label="1">已入住</el-radio>
          <el-radio :label="2">请假中</el-radio>
        </el-radio-group>

        <!-- 房间列表 -->
        <el-row :gutter="20">
          <el-col 
            v-for="room in filteredRooms" 
            :key="room?.id" 
            :span="8" 
            class="room-card-wrapper"
          >
            <el-card class="room-card">
              <template #header>
                <div class="room-header">
                  <div>房间号: {{ room?.roomNo || '未知' }}</div>
                  <div>房间类型: {{ room?.roomTypeName || '未知' }}</div>
                  <div class="room-actions">
                    <el-button type="text" @click="openRoomDetail(room?.id)" :disabled="!room?.id">查看</el-button>
                    <el-button type="text" @click="openEditRoomDialog(room)" :disabled="!room?.id">编辑</el-button>
                    <el-button 
                      type="text" 
                      :disabled="!room?.id || (room?.beds && room.beds.length > 0)"
                      @click="deleteRoom(room?.id)"
                    >删除</el-button>
                    <el-button type="primary" @click="openAddBedDialog(room?.id)" :disabled="!room?.id">新增床位</el-button>
                  </div>
                </div>
              </template>
              
              <!-- 床位列表 -->
              <div class="beds-container">
                <div 
                  v-for="bed in filteredBeds(room)" 
                  :key="bed?.id" 
                  class="bed-item"
                  :class="{
                    'bed-free': bed?.status === 0,
                    'bed-occupied': bed?.status === 1,
                    'bed-leave': bed?.status === 2
                  }"
                >
                  <div class="bed-icon">
                    <!-- 统一使用床位图标 -->
                    <svg viewBox="0 0 1024 1024" width="48" height="48">
                      <path d="M896 512V256H128v256H64v320h64v64h64v-64h640v64h64v-64h64V512h-64z m-704-192h640v192H192V320z" 
                        :fill="bed?.status === 0 ? '#67C23A' : (bed?.status === 1 ? '#409EFF' : '#E6A23C')"/>
                    </svg>
                  </div>
                  <div class="bed-info">
                    <div class="bed-number">床位号: {{ bed?.bedNo || '未知' }}</div>
                    <div class="bed-elderly" v-if="bed?.elderlyName">老人姓名: {{ bed.elderlyName }}</div>
                  </div>
                  <div class="bed-actions">
                    <el-button link size="small" @click="openEditBedDialog(bed)" :disabled="!bed?.id">编辑</el-button>
                    <el-button link size="small" :disabled="bed?.elderlyId || !bed?.id" @click="deleteBed(bed?.id)">删除</el-button>
                  </div>
                </div>
                <div v-if="(!room?.beds || room.beds.length === 0) && room" class="no-bed-tip">
                  当前房间没有安排床位
                </div>
              </div>
            </el-card>
          </el-col>
          <div v-if="filteredRooms.length === 0" class="no-room-tip">
            当前楼层暂无房间，点击"新增房间"添加
          </div>
        </el-row>
      </el-tab-pane>
    </el-tabs>
    <div v-if="floorList.length === 0" class="no-floor-tip">
      暂无楼层数据，点击"新增楼层"添加
    </div>

    <!-- 新增/编辑楼层弹窗 -->
    <el-dialog 
      v-model="addFloorDialogVisible" 
      :title="isEditFloor ? '编辑楼层' : '新增楼层'"
      width="500px"
      :close-on-click-modal="false"
    >
      <el-form :model="floorForm" ref="floorFormRef" label-width="80px" :rules="floorRules">
        <el-form-item label="楼层名称" prop="floorName">
          <el-input 
            v-model="floorForm.floorName" 
            maxlength="5"
            show-word-limit
            placeholder="请输入楼层名称"
          ></el-input>
        </el-form-item>
        <el-form-item label="排序" prop="sortNo">
          <el-input-number 
            v-model="floorForm.sortNo" 
            :min="1"
            controls-position="right"
            style="width: 100%"
          ></el-input-number>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="addFloorDialogVisible = false">取消</el-button>
          <el-button 
            v-if="isEditFloor" 
            type="danger" 
            @click="deleteFloor(floorForm)"
          >删除</el-button>
          <el-button type="primary" @click="handleSaveFloor">确定</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 楼层删除确认弹窗 -->
    <el-dialog v-model="floorDeleteDialogVisible" title="删除楼层" width="30%">
      <p>确定要删除楼层「{{ currentFloor.floorName }}」吗？删除后关联的房间和床位数据将受影响</p>
      <template #footer>
        <el-button @click="floorDeleteDialogVisible = false">取消</el-button>
        <el-button type="danger" @click="confirmDeleteFloor">确认删除</el-button>
      </template>
    </el-dialog>

    <!-- 新增/编辑房间弹窗 -->
    <el-dialog v-model="addRoomDialogVisible" :title="isEditRoom ? '编辑房间' : '新增房间'">
      <el-form :model="roomForm" ref="roomFormRef" label-width="80px" :rules="roomRules">
        <el-form-item label="房间号" prop="roomNo" required>
          <el-input v-model="roomForm.roomNo" maxlength="5"></el-input>
        </el-form-item>
        <el-form-item label="房间类型" prop="roomTypeId" required>
          <el-select v-model="roomForm.roomTypeId" placeholder="请选择">
            <el-option 
              v-for="type in roomTypeList" 
              :key="type.id" 
              :label="type.roomType" 
              :value="type.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="排序" prop="sortNo" required>
          <el-input-number v-model="roomForm.sortNo" :min="1"></el-input-number>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="addRoomDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSaveRoom">确定</el-button>
      </template>
    </el-dialog>

    <!-- 新增/编辑床位弹窗 -->
    <el-dialog v-model="addBedDialogVisible" :title="isEditBed ? '编辑床位' : '新增床位'">
      <el-form :model="bedForm" ref="bedFormRef" label-width="80px" :rules="bedRules">
        <el-form-item label="床位号" prop="bedNo" required>
          <el-input v-model="bedForm.bedNo" maxlength="10"></el-input>
        </el-form-item>
        <el-form-item label="排序" prop="sortNo" required>
          <el-input-number v-model="bedForm.sortNo" :min="1"></el-input-number>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="addBedDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSaveBed">确定</el-button>
      </template>
    </el-dialog>

    <!-- 房间详情弹窗 -->
    <el-dialog v-model="roomDetailDialogVisible" title="房间详情">
      <div v-if="currentRoom" class="room-detail">
        <div class="detail-row">
          <span>房间号: {{ currentRoom.roomNo }}</span>
          <span>房间类型: {{ currentRoom.roomTypeName }}</span>
        </div>
        <div class="detail-row">
          <span>总床位数: {{ currentRoom.totalBeds || 0 }}</span>
          <span>入住床位数: {{ currentRoom.occupiedBeds || 0 }}</span>
          <span>入住率: {{ currentRoom.occupancyRate || 0 }}%</span>
        </div>
        <el-table :data="currentRoom.beds || []" border style="width: 100%; margin-top: 10px;">
          <el-table-column prop="bedNo" label="床位号"></el-table-column>
          <el-table-column prop="elderlyName" label="老人姓名"></el-table-column>
          <el-table-column label="护理等级">
            <template #default="scope">{{ scope.row.careLevel || '未知' }}</template>
          </el-table-column>
          <el-table-column label="入住期限">
            <template #default="scope">{{ scope.row.stayPeriod || '未设置' }}</template>
          </el-table-column>
        </el-table>
      </div>
    </el-dialog>

    <!-- 老人入住弹窗 -->
    <el-dialog v-model="checkInDialogVisible" title="老人入住登记">
      <el-form :model="elderlyForm" ref="elderlyFormRef" label-width="80px" :rules="elderlyRules">
        <el-form-item label="床位号" prop="bedNo">
          <el-input v-model="elderlyForm.bedNo" disabled></el-input>
        </el-form-item>
        <el-form-item label="老人姓名" prop="name" required>
          <el-input v-model="elderlyForm.name"></el-input>
        </el-form-item>
        <el-form-item label="性别" prop="gender" required>
          <el-radio-group v-model="elderlyForm.gender">
            <el-radio label="男">男</el-radio>
            <el-radio label="女">女</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="年龄" prop="age">
          <el-input-number v-model="elderlyForm.age" :min="0"></el-input-number>
        </el-form-item>
        <el-form-item label="护理等级" prop="careLevel">
          <el-select v-model="elderlyForm.careLevel" placeholder="请选择">
            <el-option label="一级护理" value="1"></el-option>
            <el-option label="二级护理" value="2"></el-option>
            <el-option label="三级护理" value="3"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="checkInDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmCheckIn">确认入住</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed, watch } from 'vue'
import { 
  ElMessage, ElMessageBox, ElForm, ElFormItem, ElInput, 
  ElInputNumber, ElSelect, ElOption, ElDialog, ElTabs, 
  ElTabPane, ElCard, ElRow, ElCol, ElButton, ElRadioGroup, 
  ElRadio, ElTable, ElTableColumn, ElIcon
} from 'element-plus'
import { Edit, Delete } from '@element-plus/icons-vue'

// 引入API接口（请确保实际项目中接口路径和方法正确）
import { 
  getFloorsWithRelations, addFloor, delFloor, updateFloor,
  listRoom, getRoom, addRoom, delRoom, updateRoom,
  getBed, addBed, updateBed, delBed,
  checkInElderly
} from '@/api/bed/bed'
import { listRoomType } from '@/api/bed/bed'

// 表单引用
const floorFormRef = ref(null)
const roomFormRef = ref(null)
const bedFormRef = ref(null)
const elderlyFormRef = ref(null)

// 表单验证规则
const floorRules = {
  floorName: [{ required: true, message: '请输入楼层名称', trigger: 'blur' }],
  sortNo: [{ required: true, message: '请输入排序号', trigger: 'blur' }]
}
const roomRules = {
  roomNo: [{ required: true, message: '请输入房间号', trigger: 'blur' }],
  roomTypeId: [{ required: true, message: '请选择房间类型', trigger: 'change' }],
  sortNo: [{ required: true, message: '请输入排序号', trigger: 'blur' }]
}
const bedRules = {
  bedNo: [{ required: true, message: '请输入床位号', trigger: 'blur' }],
  sortNo: [{ required: true, message: '请输入排序号', trigger: 'blur' }]
}
const elderlyRules = {
  name: [{ required: true, message: '请输入老人姓名', trigger: 'blur' }],
  gender: [{ required: true, message: '请选择性别', trigger: 'change' }]
}

// 状态管理
const activeFloorKey = ref('')
const bedStatus = ref(0) // 0:空闲 1:已入住 2:请假中
const floorList = ref([])
const roomTypeList = ref([])

// 当前选中楼层ID
const currentFloorId = computed(() => {
  const floor = floorList.value.find(item => item.id.toString() === activeFloorKey.value)
  return floor ? Number(floor.id) : null
})

// 弹窗控制
const addFloorDialogVisible = ref(false)
const floorDeleteDialogVisible = ref(false)
const addRoomDialogVisible = ref(false)
const addBedDialogVisible = ref(false)
const roomDetailDialogVisible = ref(false)
const checkInDialogVisible = ref(false)

// 编辑状态标识
const isEditFloor = ref(false)
const isEditRoom = ref(false)
const isEditBed = ref(false)

// 表单数据
const floorForm = reactive({
  id: null,
  floorName: '',
  sortNo: 1
})
const currentFloor = reactive({
  id: null,
  floorName: ''
})
const roomForm = reactive({
  id: null,
  roomNo: '',
  roomTypeId: null,
  sortNo: 1,
  floorId: null
})
const bedForm = reactive({
  id: null,
  bedNo: '',
  sortNo: 1,
  roomId: null
})
const elderlyForm = reactive({
  bedId: null,
  bedNo: '',
  name: '',
  gender: '男',
  age: null,
  careLevel: null
})

// 辅助状态
const currentRoom = ref(null)
const roomsByFloor = ref([])

// ========== 接口请求方法 ==========

// 获取楼层列表
const fetchFloors = async () => {
  try {
    const res = await getFloorsWithRelations()
    const validFloors = (res.data || []).filter(floor => floor.id != null && floor.floorName)
      .sort((a, b) => (a.sortNo || 0) - (b.sortNo || 0))
    floorList.value = validFloors
    if (validFloors.length > 0 && !activeFloorKey.value) {
      activeFloorKey.value = validFloors[0].id.toString()
      fetchRoomsByFloor(Number(validFloors[0].id))
    }
  } catch (error) {
    ElMessage.error('获取楼层失败：' + (error.message || '网络错误'))
  }
}

// 获取房间类型列表
const fetchRoomTypes = async () => {
  try {
    const res = await listRoomType()
    roomTypeList.value = (res.rows || []).map(type => ({
      ...type,
      id: Number(type.id)
    }))
  } catch (error) {
    ElMessage.error('获取房间类型失败：' + (error.message || '网络错误'))
  }
};

// 根据楼层ID获取房间列表
const fetchRoomsByFloor = async (floorId) => {
  if (!floorId) {
    roomsByFloor.value = []
    return
  }
  try {
    const res = await listRoom({ floorId })
    const rawRooms = res.data || []
    const validRooms = rawRooms
      .filter(room => room.id != null && Number(room.floorId) === floorId)
      .map(room => {
        const roomTypeId = Number(room.roomTypeId)
        const matchedType = roomTypeList.value.find(t => t.id === roomTypeId)
        // 修正：映射后端床位字段（bedId→id，bedStatus→status）
        const beds = (room.beds || []).map(bed => ({
          ...bed,
          id: bed.bedId,          // 后端返回bedId映射为前端id
          status: bed.bedStatus ?? 0, // 后端bedStatus映射为前端status
          elderlyId: bed.elderlyId   // 保留老人ID用于判断
        }))
        return {
          ...room,
          id: Number(room.id),
          floorId: Number(room.floorId),
          roomTypeName: matchedType ? matchedType.roomType : '未知类型',
          beds
        }
      })
      .sort((a, b) => (a.sortNo || 0) - (b.sortNo || 0))
    roomsByFloor.value = validRooms
  } catch (error) {
    ElMessage.error('获取房间失败：' + (error.message || '网络错误'))
    roomsByFloor.value = []
  }
}

// 获取单个床位详情
const fetchBedDetail = async (bedId) => {
  if (!bedId) return null
  try {
    const res = await getBed(bedId)
    return res.data || {}
  } catch (error) {
    ElMessage.error('获取床位详情失败：' + (error.message || '网络错误'))
    return null
  }
}

// ========== 楼层相关方法 ==========

// 打开楼层编辑/新增弹窗（独立逻辑）
const openAddFloorDialog = (floor = null) => {
  if (floor) {
    // 编辑模式：填充数据
    isEditFloor.value = true
    floorForm.id = floor.id
    floorForm.floorName = floor.floorName
    floorForm.sortNo = floor.sortNo || 1
  } else {
    // 新增模式：清空数据
    isEditFloor.value = false
    floorForm.id = null
    floorForm.floorName = ''
    floorForm.sortNo = 1
  }
  addFloorDialogVisible.value = true
}

// 保存楼层
const handleSaveFloor = async () => {
  if (!floorFormRef.value) return
  floorFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        if (isEditFloor.value) {
          await updateFloor(floorForm)
          ElMessage.success('楼层编辑成功')
        } else {
          await addFloor(floorForm)
          ElMessage.success('楼层新增成功')
        }
        addFloorDialogVisible.value = false
        fetchFloors() // 刷新楼层列表
      } catch (error) {
        // 只显示后端返回的错误信息，不添加前缀
        ElMessage.error(error.message || '操作失败')
      }
    }
  })
}

// 打开楼层删除确认弹窗
const deleteFloor = (floor) => {
  currentFloor.id = floor.id
  currentFloor.floorName = floor.floorName
  floorDeleteDialogVisible.value = true
}

// 确认删除楼层
const confirmDeleteFloor = async () => {
  try {
    await delFloor(currentFloor.id)
    floorDeleteDialogVisible.value = false
    ElMessage.success('楼层删除成功')
    await fetchFloors()
    if (floorList.value.length === 0) {
      activeFloorKey.value = ''
      roomsByFloor.value = []
    }
  } catch (error) {
    ElMessage.error(error.message || '删除失败')
  }
}

// ========== 房间相关方法 ==========

// 打开房间编辑/新增弹窗
const openAddRoomDialog = (room = null) => {
  console.log('调用openAddRoomDialog，room参数：', room)
  if (!currentFloorId.value && !room) {
    ElMessage.warning('请先选择楼层')
    return
  }
  if (room) {
    console.log('进入【编辑房间】逻辑')
    isEditRoom.value = true
    roomForm.id = room.id
    roomForm.roomNo = room.roomNo
    roomForm.roomTypeId = room.roomTypeId
    roomForm.sortNo = room.sortNo || 1
    roomForm.floorId = room.floorId
  } else {
    console.log('进入【新增房间】逻辑')
    isEditRoom.value = false
    roomForm.id = null
    roomForm.roomNo = ''
    roomForm.roomTypeId = null
    roomForm.sortNo = 1
    roomForm.floorId = currentFloorId.value
  }
  addRoomDialogVisible.value = true
}
// 编辑房间快捷入口
const openEditRoomDialog = (room) => {
  openAddRoomDialog(room)
}

// 保存房间
const handleSaveRoom = async () => {
  if (!roomFormRef.value) return
  roomFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        const params = {
          ...roomForm,
          roomTypeId: Number(roomForm.roomTypeId)
        }
        if (isEditRoom.value) {
          await updateRoom(params)
          ElMessage.success('房间编辑成功')
        } else {
          await addRoom(params)
          ElMessage.success('房间新增成功')
        }
        addRoomDialogVisible.value = false
        fetchRoomsByFloor(currentFloorId.value)
      } catch (error) {
        ElMessage.error(error.message || '操作失败')
      }
    }
  })
}

// 查看房间详情
const openRoomDetail = async (roomId) => {
  if (!roomId) return
  try {
    const res = await getRoom(roomId)
    const roomData = res.data || {}
    const roomTypeId = Number(roomData.roomTypeId)
    const type = roomTypeList.value.find(t => t.id === roomTypeId)
    const beds = (roomData.beds || []).map(bed => ({ 
      ...bed, 
      id: bed.bedId,
      status: bed.bedStatus ?? 0 
    }))
    currentRoom.value = {
      ...roomData,
      roomTypeName: type ? type.roomType : '未知类型',
      beds
    }
    roomDetailDialogVisible.value = true
  } catch (error) {
    ElMessage.error('获取房间详情失败：' + (error.message || '网络错误'))
  }
}

// 删除房间
const deleteRoom = async (roomId) => {
  if (!roomId) return
  const room = roomsByFloor.value.find(r => r.id === roomId)
  if (room?.beds?.length > 0) {
    ElMessage.warning('该房间下有床位，无法删除')
    return
  }
  try {
    await ElMessageBox.confirm('确定删除该房间吗？', '提示', { type: 'warning' })
    await delRoom(roomId)
    ElMessage.success('删除成功')
    fetchRoomsByFloor(currentFloorId.value)
  } catch (error) {
    if (error === 'cancel') return
    ElMessage.error(error.message || '删除失败')
  }
}

// ========== 床位相关方法 ==========

// 打开床位编辑/新增弹窗
const openAddBedDialog = (roomId) => {
  if (!roomId) {
    ElMessage.warning('请选择房间')
    return
  }
  bedForm.roomId = roomId
  bedForm.bedNo = ''
  bedForm.sortNo = 1
  bedForm.id = null
  isEditBed.value = false
  addBedDialogVisible.value = true
}

// 编辑床位
const openEditBedDialog = async (bed) => {
  if (!bed?.id) return
  bedForm.id = bed.id
  bedForm.bedNo = bed.bedNo
  bedForm.sortNo = bed.sortNo || 1
  bedForm.roomId = bed.roomId
  isEditBed.value = true
  addBedDialogVisible.value = true
}

// 保存床位
const handleSaveBed = async () => {
  if (!bedFormRef.value) return
  bedFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        const params = {
          ...bedForm,
          roomId: Number(bedForm.roomId)
        }
        if (isEditBed.value) {
          await updateBed(params)
          ElMessage.success('床位编辑成功')
        } else {
          await addBed(params)
          ElMessage.success('床位新增成功')
        }
        addBedDialogVisible.value = false
        fetchRoomsByFloor(currentFloorId.value)
      } catch (error) {
        ElMessage.error(error.message || '操作失败')
      }
    }
  })
}

// 删除床位（修正：通过elderlyId判断是否有老人）
const deleteBed = async (bedId) => {
  if (!bedId) return
  const hasElderly = roomsByFloor.value.some(room => 
    room.beds?.some(bed => bed.id === bedId && bed.elderlyId != null)
  )
  if (hasElderly) {
    ElMessage.warning('该床位下有老人，无法删除')
    return
  }
  try {
    await ElMessageBox.confirm('确定删除该床位吗？', '提示', { type: 'warning' })
    await delBed(bedId)
    ElMessage.success('删除成功')
    fetchRoomsByFloor(currentFloorId.value)
  } catch (error) {
    if (error === 'cancel') return
    ElMessage.error(error.message || '删除失败')
  }
}

// ========== 老人入住相关 ==========

// 打开老人入住弹窗
const openCheckInDialog = async (bedId) => {
  if (!bedId) return
  const bed = await fetchBedDetail(bedId)
  if (!bed) return
  elderlyForm.bedId = bedId
  elderlyForm.bedNo = bed.bedNo || ''
  elderlyForm.name = ''
  elderlyForm.gender = '男'
  elderlyForm.age = null
  elderlyForm.careLevel = null
  checkInDialogVisible.value = true
}

// 确认老人入住
const confirmCheckIn = async () => {
  if (!elderlyFormRef.value) return
  elderlyFormRef.value.validate(async (valid) => {
    if (valid) {
      const { bedId, ...elderlyInfo } = elderlyForm
      try {
        await checkInElderly(bedId, elderlyInfo)
        ElMessage.success('老人入住成功')
        checkInDialogVisible.value = false
        fetchRoomsByFloor(currentFloorId.value)
      } catch (error) {
        ElMessage.error(error.message || '入住失败')
      }
    }
  })
}

// ========== 过滤与监听 ==========

// 过滤当前楼层的房间
const filteredRooms = computed(() => {
  return Array.isArray(roomsByFloor.value) ? roomsByFloor.value : []
})

// 根据床位状态过滤
const filteredBeds = (room) => {
  if (!room || !Array.isArray(room.beds)) return []
  return room.beds.filter(bed => bed.status === bedStatus.value)
}

// 监听楼层切换
watch(activeFloorKey, (newFloorId) => {
  if (newFloorId) {
    fetchRoomsByFloor(Number(newFloorId))
  }
})

// 初始化
onMounted(async () => {
  await fetchRoomTypes()
  await fetchFloors()
})
</script>

<style scoped>
/* 整体容器 - 添加渐变背景 */
.bed-type-container {
  padding: 24px;
  background: linear-gradient(135deg, #f5f7fa 0%, #e8f4f8 50%, #f0f9ff 100%);
  min-height: calc(100vh - 100px);
}

/* 楼层标签样式（编辑/删除按钮独立） - 现代化设计 */
.tab-label {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 8px 16px;
  min-width: 140px;
  transition: all 0.3s;
  border-radius: 8px;
}

.floor-name {
  font-size: 15px;
  font-weight: 600;
  color: #606266;
  flex-shrink: 0;
  transition: all 0.3s;
}

.tab-label.active {
  background: linear-gradient(135deg, #ecf5ff 0%, #e8f4ff 100%);
}

.tab-label.active .floor-name {
  color: #409eff;
  font-size: 16px;
}

.floor-actions {
  display: flex;
  gap: 8px;
  align-items: center;
  opacity: 0;
  transition: opacity 0.3s;
}

.tab-label:hover .floor-actions {
  opacity: 1;
}

.floor-edit-btn, .floor-delete-btn {
  padding: 2px 6px !important;
  font-size: 12px;
  height: 24px;
  display: flex;
  align-items: center;
  gap: 4px;
}

.floor-edit-btn {
  color: #409eff;
}

.floor-edit-btn:hover {
  color: #66b1ff;
  background: #ecf5ff;
}

.floor-delete-btn {
  color: #f56c6c;
}

.floor-delete-btn:hover {
  color: #f78989;
  background: #fef0f0;
}

/* 房间卡片样式 - 现代化设计 */
.room-card-wrapper {
  margin-bottom: 24px;
}
.room-card {
  height: 100%;
  display: flex;
  flex-direction: column;
  border: none;
  border-radius: 16px;
  overflow: hidden;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  background: #ffffff;
}
.room-card:hover {
  transform: translateY(-4px);
  box-shadow: 0 12px 24px rgba(64, 158, 255, 0.2);
}
.room-header {
  display: flex;
  flex-direction: column;
  gap: 8px;
}
.room-header > div:first-child {
  font-size: 14px;
  font-weight: 600;
  color: #303133;
}
.room-header > div:nth-child(2) {
  font-size: 13px;
  color: #606266;
}
.room-actions {
  display: flex;
  gap: 6px;
  flex-wrap: wrap;
  margin-top: 4px;
}
.room-actions button {
  margin-left: 0;
  padding: 4px 10px;
  font-size: 13px;
}

/* 床位容器样式 - 优化布局 */
.beds-container {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(160px, 1fr));
  gap: 16px;
  padding: 12px 0;
}
.bed-item {
  border: 2px solid #e4e7ed;
  border-radius: 12px;
  padding: 16px 12px;
  display: flex;
  flex-direction: column;
  align-items: center;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  background: linear-gradient(135deg, #ffffff 0%, #f9fafb 100%);
  position: relative;
  overflow: hidden;
}
.bed-item::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  height: 4px;
  background: linear-gradient(90deg, transparent, currentColor, transparent);
  opacity: 0;
  transition: opacity 0.3s;
}
.bed-item:hover {
  box-shadow: 0 8px 20px rgba(64, 158, 255, 0.2);
  transform: translateY(-4px) scale(1.03);
}
.bed-item:hover::before {
  opacity: 1;
}
.bed-icon {
  margin-bottom: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
}
.bed-icon svg {
  filter: drop-shadow(0 2px 4px rgba(0, 0, 0, 0.1));
}
.bed-info {
  text-align: center;
  margin-bottom: 8px;
  width: 100%;
}
.bed-number {
  font-size: 13px;
  color: #409eff;
  font-weight: 500;
  margin-bottom: 4px;
}
.bed-elderly {
  font-size: 12px;
  color: #606266;
}
.bed-free {
  border-color: #67c23a;
  background: linear-gradient(135deg, #f0f9ff 0%, #e8f8f5 100%);
  color: #67c23a;
}
.bed-free:hover {
  box-shadow: 0 8px 20px rgba(103, 194, 58, 0.25);
}
.bed-occupied {
  border-color: #409eff;
  background: linear-gradient(135deg, #ecf5ff 0%, #e8f4ff 100%);
  color: #409eff;
}
.bed-occupied:hover {
  box-shadow: 0 8px 20px rgba(64, 158, 255, 0.3);
}
.bed-leave {
  border-color: #e6a23c;
  background: linear-gradient(135deg, #fdf6ec 0%, #fef5e7 100%);
  color: #e6a23c;
}
.bed-leave:hover {
  box-shadow: 0 8px 20px rgba(230, 162, 60, 0.25);
}
.bed-actions {
  display: flex;
  gap: 4px;
  flex-wrap: wrap;
  justify-content: center;
  width: 100%;
}
.bed-actions button {
  padding: 2px 6px;
  font-size: 12px;
}

/* 提示文本样式 */
.no-bed-tip, .no-room-tip, .no-floor-tip {
  text-align: center;
  color: #999;
  padding: 20px;
  margin-top: 20px;
  background: #f5f7fa;
  border-radius: 4px;
}

/* 房间详情样式 */
.room-detail {
  display: flex;
  flex-direction: column;
}
.detail-row {
  display: flex;
  justify-content: space-between;
  margin-bottom: 8px;
  flex-wrap: wrap;
  gap: 16px;
}
.detail-row span {
  color: #606266;
  padding: 4px 0;
}

/* 弹窗样式调整 */
:deep(.el-dialog__header) {
  background: #f5f7fa;
  border-bottom: 1px solid #e4e7ed;
  padding: 16px 20px;
}

:deep(.el-dialog__title) {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

:deep(.el-dialog__body) {
  padding: 20px;
}

:deep(.el-dialog__footer) {
  padding: 12px 20px;
  border-top: 1px solid #e4e7ed;
  background: #f5f7fa;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

:deep(.el-form-item) {
  margin-bottom: 18px;
}

:deep(.el-form-item__label) {
  font-weight: 500;
  color: #606266;
}

:deep(.el-input__count) {
  color: #909399;
  font-size: 12px;
}

/* 卡片头部样式 */
:deep(.el-card__header) {
  background: #f5f7fa;
  border-bottom: 1px solid #e4e7ed;
  padding: 16px 20px;
}

/* 床位状态筛选样式 */
.el-radio-group {
  margin-bottom: 20px;
  padding: 12px 16px;
  background: #ffffff;
  border-radius: 4px;
  border: 1px solid #e4e7ed;
}
:deep(.el-radio) {
  margin-right: 24px;
}
:deep(.el-radio__label) {
  font-weight: 500;
  color: #606266;
}
:deep(.el-radio.is-checked .el-radio__label) {
  color: #409eff;
}

/* 顶部按钮样式 */
:deep(.mb-4 .el-button) {
  border-radius: 4px;
}

/* Tab栏样式 */
:deep(.el-tabs__header) {
  background: #ffffff;
  padding: 12px 16px;
  border-radius: 4px;
  border: 1px solid #e4e7ed;
  margin-bottom: 24px;
}
:deep(.el-tabs--card > .el-tabs__header) {
  border-bottom: none;
}
:deep(.el-tabs--card > .el-tabs__header .el-tabs__item) {
  border-radius: 4px;
}

/* 床位按钮美化 */
.bed-actions button {
  border-radius: 6px;
  transition: all 0.3s;
}

/* 房间操作按钮 */
.room-actions :deep(.el-button) {
  border-radius: 6px;
}
.room-actions :deep(.el-button--primary) {
  background: linear-gradient(135deg, #409eff 0%, #66b1ff 100%);
  border: none;
}
.room-actions :deep(.el-button--text) {
  color: #409eff;
  font-weight: 500;
}
.room-actions :deep(.el-button--text:hover) {
  background: #ecf5ff;
  color: #66b1ff;
}

/* 床位信息优化 */
.bed-number {
  font-size: 15px;
  font-weight: 600;
  margin-bottom: 6px;
}
.bed-icon svg {
  filter: drop-shadow(0 2px 4px rgba(0, 0, 0, 0.15));
  transition: all 0.3s;
}
.bed-item:hover .bed-icon svg {
  filter: drop-shadow(0 4px 8px rgba(0, 0, 0, 0.2));
  transform: scale(1.1);
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .beds-container {
    grid-template-columns: repeat(auto-fill, minmax(140px, 1fr));
  }
}
@media (max-width: 768px) {
  .bed-type-container {
    padding: 16px;
  }
  .room-card-wrapper {
    margin-bottom: 16px;
  }
  .beds-container {
    grid-template-columns: repeat(auto-fill, minmax(120px, 1fr));
    gap: 12px;
  }
  .bed-item {
    padding: 12px 8px;
  }
  :deep(.el-col-8) {
    max-width: 100%;
    flex: 0 0 100%;
  }
}

/* 空状态提示美化 */
.no-bed-tip, .no-room-tip, .no-floor-tip {
  text-align: center;
  color: #909399;
  padding: 40px 20px;
  margin-top: 20px;
  background: linear-gradient(135deg, #ffffff 0%, #f5f7fa 100%);
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
  font-size: 14px;
}
</style>